
package il.ac.tau.dbcourse.gui;

import java.io.BufferedInputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.eclipse.swt.graphics.Image;
import org.w3c.dom.Document;

public class AlbumArtProvider extends AlbumWidget{
	static DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	static DocumentBuilder builder;
	static final int ICON_WIDTH = 100;
	static final int ICON_HEIGHT = 100;	
	static Map<String, Image> imageMap = new HashMap<String, Image>();
	
	static {
		try {
			builder = factory.newDocumentBuilder();
						
	    	Image img = new Image(MainGui.display, "Images/noimage.gif");
	    	imageMap.put("NO_IMAGE", img);
			
		} catch (ParserConfigurationException e) {
			e.printStackTrace();		
		}
	}    				
	
    public static Image getAlbumArt(int mode, String artist, String album) {
    	String key = artist + "\t" + album;
		Image result = imageMap.get(key);
		//if (result != null) return result;				
		
		try {
			if (mode==1)
			{
			String url = "http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=b25b959554ed76058ac220b7b2e0a026&artist=" + URLEncoder.encode(artist, "UTF-8") + "&album=" + URLEncoder.encode(album, "UTF-8");
			Document doc = builder.parse(url);
		
			XPath xpath = XPathFactory.newInstance().newXPath();
		    String imageUrl = (String) xpath.evaluate("//image[@size='medium']/text()", doc, XPathConstants.STRING);		    
		    		    
		    if (imageUrl.length() > 0) {
		    	result = new Image(MainGui.display, new BufferedInputStream(new URL(imageUrl).openStream()));
		    }		    
		    else {
		    	result = imageMap.get("NO_IMAGE");
		    }
			System.out.println(url);
			imageMap.put(key, result);
			return result;
			}
			else
			{
				result = imageMap.get("NO_IMAGE");
				imageMap.put(key, result);
				return result;
				
			}
		} 
		
		catch (Exception e) {
			return imageMap.get("NO_IMAGE");
		}	    	    
    }       
}